import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col, Tree, Checkbox, Avatar } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined, ExclamationCircleOutlined, UserOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'
import { listRoles, getRole, getRolePermissions, setRolePermissions, getRoleUsers, setRoleUsers, createRole, updateRole, deleteRole } from '../../../api/role'

const { confirm } = Modal
const { TabPane } = Tabs

const Role = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentRole, setCurrentRole] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewRole, setViewRole] = useState(null)
    const [permissionVisible, setPermissionVisible] = useState(false)
    const [currentPermissions, setCurrentPermissions] = useState([])
    const [userRoleVisible, setUserRoleVisible] = useState(false)
    const [selectedUsers, setSelectedUsers] = useState([])

    // 权限数据
    const [permissions, setPermissions] = useState([])

    // 权限数据结构
    const defaultPermissions = [
        {
            id: 1,
            name: '系统管理',
            key: 'system',
            children: [
                { id: 101, name: '用户管理', key: 'system:user' },
                { id: 102, name: '角色管理', key: 'system:role' },
                { id: 103, name: '部门管理', key: 'system:department' },
                { id: 104, name: '权限管理', key: 'system:permission' }
            ]
        },
        {
            id: 2,
            name: '人事管理',
            key: 'hr',
            children: [
                { id: 201, name: '员工管理', key: 'hr:employee' },
                { id: 202, name: '考勤管理', key: 'hr:attendance' },
                { id: 203, name: '薪资管理', key: 'hr:salary' },
                { id: 204, name: '培训管理', key: 'hr:training' }
            ]
        },
        {
            id: 3,
            name: '招聘管理',
            key: 'recruitment',
            children: [
                { id: 301, name: '职位管理', key: 'recruitment:position' },
                { id: 302, name: '简历管理', key: 'recruitment:resume' },
                { id: 303, name: '面试管理', key: 'recruitment:interview' }
            ]
        }
    ]
    
    // 用户列表
    const [users, setUsers] = useState([])

    useEffect(() => {
        fetchRoles()
        fetchPermissions()
    }, [pagination.current, pagination.pageSize])

    // 获取角色数据
    const fetchRoles = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize
            }
            const res = await listRoles(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('获取角色列表失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 获取权限数据
    const fetchPermissions = async () => {
        try {
            const res = await getPermissions()
            setPermissions(res.data || defaultPermissions)
        } catch (error) {
            console.error('获取权限列表失败', error)
            setPermissions(defaultPermissions)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true)
        try {
            const params = {
                page: 1,
                pageSize: pagination.pageSize,
                keyword: value
            }
            const res = await listRoles(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                current: 1,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('搜索失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 添加角色
    const handleAdd = () => {
        setCurrentRole(null)
        setVisible(true)
    }

    // 编辑角色
    const handleEdit = (record) => {
        setCurrentRole(record)
        setVisible(true)
    }

    // 查看角色详情
    const handleView = async (id) => {
        try {
            const res = await getRole(id)
            setViewRole(res.data)
            setViewVisible(true)
            // 获取角色权限
            const permRes = await getRolePermissions(id)
            setCurrentPermissions(permRes.data || [])
        } catch (error) {
            message.error('获取角色详情失败')
            console.error(error)
        }
    }

    // 删除角色
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这个角色吗？此操作不可恢复，且会影响所有关联的用户。',
            async onOk() {
                try {
                    // 获取角色详情，检查是否有用户关联
                    const res = await getRole(id)
                    if (res.data && res.data.user_count > 0) {
                        message.error(`该角色下有${res.data.user_count}个用户，无法删除`)
                        return
                    }
                    
                    // 调用删除API
                    await deleteRole(id)
                    message.success('删除成功')
                    fetchRoles()
                } catch (error) {
                    message.error('删除失败')
                    console.error(error)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            if (currentRole) {
                // 编辑角色
                await updateRole(currentRole.id, values)
                message.success('编辑成功')
            } else {
                // 添加角色
                await createRole(values)
                message.success('添加成功')
            }
            setVisible(false)
            fetchRoles()
        } catch (error) {
            message.error(currentRole ? '编辑失败' : '添加失败')
            console.error(error)
        }
    }

    // 打开权限分配模态框
    const handlePermission = async (record) => {
        setCurrentRole(record)
        try {
            const res = await getRolePermissions(record.id)
            setCurrentPermissions(res.data || [])
            setPermissionVisible(true)
        } catch (error) {
            message.error('获取角色权限失败')
            console.error(error)
        }
    }

    // 处理权限变更
    const handlePermissionChange = (checkedKeys) => {
        setCurrentPermissions(checkedKeys)
    }

    // 保存权限设置
    const handleSavePermissions = async () => {
        try {
            await setRolePermissions(currentRole.id, currentPermissions)
            message.success('权限设置保存成功')
            setPermissionVisible(false)
        } catch (error) {
            message.error('保存权限设置失败')
            console.error(error)
        }
    }

    // 打开用户角色分配模态框
    const handleUserRole = async (record) => {
        setCurrentRole(record)
        try {
            // 获取所有用户
            const allUsersRes = await getRoleUsers(record.id)
            setUsers(allUsersRes.data.all || [])
            // 获取拥有该角色的用户
            setSelectedUsers(allUsersRes.data.selected || [])
            setUserRoleVisible(true)
        } catch (error) {
            message.error('获取用户列表失败')
            console.error(error)
        }
    }

    // 处理用户角色变更
    const handleUserRoleChange = (checkedValues) => {
        setSelectedUsers(checkedValues)
    }

    // 保存用户角色设置
    const handleSaveUserRoles = async () => {
        try {
            await setRoleUsers(currentRole.id, selectedUsers)
            message.success('用户角色分配保存成功')
            setUserRoleVisible(false)
            fetchRoles() // 刷新角色列表，更新用户数量
        } catch (error) {
            message.error('保存用户角色分配失败')
            console.error(error)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '角色名称',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <a onClick={() => handleView(record.id)}>{text}</a>
            )
        },
        {
            title: '角色描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true
        },
        {
            title: '用户数量',
            dataIndex: 'user_count',
            key: 'user_count'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = status === 1 ? 'green' : 'volcano'
                let text = status === 1 ? '启用' : '禁用'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at'
        },
        {
            title: '操作',
            key: 'action',
            width: 280,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        icon={<KeyOutlined />} 
                        onClick={() => handlePermission(record)}
                    >
                        权限
                    </Button>
                    <Button 
                        type="text" 
                        icon={<UserOutlined />} 
                        onClick={() => handleUserRole(record)}
                    >
                        用户
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="role-container">
            <Card title="角色管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加角色
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchRoles}
                    searchPlaceholder="搜索角色名称/描述"
                />
            </Card>

            {/* 角色表单模态框 */}
            <Modal
                title={currentRole ? '编辑角色' : '添加角色'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentRole || { status: 1 }}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="name"
                        label="角色名称"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                    >
                        <input placeholder="请输入角色名称" />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="角色描述"
                    >
                        <textarea placeholder="请输入角色描述" rows={4} />
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value={1}>启用</option>
                            <option value={0}>禁用</option>
                        </select>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 角色详情模态框 */}
            <Modal
                title="角色详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewRole && (
                    <Tabs defaultActiveKey="1">
                        <TabPane tab="基本信息" key="1">
                            <Descriptions bordered column={2}>
                                <Descriptions.Item label="ID">{viewRole.id}</Descriptions.Item>
                                <Descriptions.Item label="角色名称">{viewRole.name}</Descriptions.Item>
                                <Descriptions.Item label="角色描述" span={2}>{viewRole.description}</Descriptions.Item>
                                <Descriptions.Item label="用户数量">{viewRole.user_count}</Descriptions.Item>
                                <Descriptions.Item label="状态">
                                    <Tag color={viewRole.status === 1 ? 'green' : 'volcano'}>
                                        {viewRole.status === 1 ? '启用' : '禁用'}
                                    </Tag>
                                </Descriptions.Item>
                                <Descriptions.Item label="创建时间">{viewRole.created_at}</Descriptions.Item>
                                <Descriptions.Item label="更新时间">{viewRole.updated_at}</Descriptions.Item>
                            </Descriptions>
                        </TabPane>
                        <TabPane tab="权限信息" key="2">
                            <Tree
                                checkable
                                disabled
                                defaultExpandAll
                                treeData={permissions}
                                checkedKeys={currentPermissions}
                                fieldNames={{ title: 'name', key: 'id' }}
                            />
                        </TabPane>
                        <TabPane tab="用户列表" key="3">
                            <ul style={{ listStyle: 'none', padding: 0 }}>
                                {users.length > 0 ? (
                                    users.map(user => (
                                        <li key={user.id} style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0' }}>
                                            <Space>
                                                <Avatar icon={<UserOutlined />} />
                                                <span>{user.name}</span>
                                                <Tag color="blue">{user.department}</Tag>
                                                <span>{user.position}</span>
                                            </Space>
                                        </li>
                                    ))
                                ) : (
                                    <div style={{ textAlign: 'center', padding: '20px 0', color: '#999' }}>
                                        暂无用户
                                    </div>
                                )}
                            </ul>
                        </TabPane>
                    </Tabs>
                )}
            </Modal>

            {/* 权限分配模态框 */}
            <Modal
                title={`权限分配 - ${currentRole?.name}`}
                open={permissionVisible}
                onCancel={() => setPermissionVisible(false)}
                onOk={handleSavePermissions}
                width={700}
            >
                <Tree
                    checkable
                    defaultExpandAll
                    treeData={permissions}
                    checkedKeys={currentPermissions}
                    onCheck={handlePermissionChange}
                    fieldNames={{ title: 'name', key: 'id' }}
                />
            </Modal>

            {/* 用户角色分配模态框 */}
            <Modal
                title={`用户分配 - ${currentRole?.name}`}
                open={userRoleVisible}
                onCancel={() => setUserRoleVisible(false)}
                onOk={handleSaveUserRoles}
                width={700}
            >
                <Checkbox.Group 
                    style={{ width: '100%' }} 
                    value={selectedUsers}
                    onChange={handleUserRoleChange}
                >
                    <Row>
                        {users.map(user => (
                            <Col span={8} key={user.id} style={{ marginBottom: 16 }}>
                                <Checkbox value={user.id}>
                                    <Space>
                                        {user.name}
                                        <Tag color="blue">{user.department}</Tag>
                                    </Space>
                                </Checkbox>
                            </Col>
                        ))}
                    </Row>
                </Checkbox.Group>
            </Modal>
        </div>
    )
}

export default Role